﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using MedicinaMuncii.BL.Contracts;
using MedicinaMuncii.DAL.Contracts;
using MedicinaMuncii.Entities;
using MedicinaMuncii.Repository.Contracts;
using MedicinaMuncii.IoC;

namespace MedicinaMuncii.BL.Implementations
{
    /// <summary>
    /// Base entity service class, provides easy access to domain repository
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class EntityService<T> : IEntityService<T> where T : IObjectWithChangeTracker
    {
        protected IGenericRepository<T> _repository;

        protected EntityService()
        {
            
        }

        public T GetByID(Expression<Func<T, bool>> idSelector, params string[] includes)
        {
            return _repository.Single(idSelector, includes);
        }
        
        public IList<T> GetAll(params string[] includes)
        {
            return _repository.GetAll(includes).ToList();
        }

        public virtual void Add(T entity)
        {
            IUnitOfWork unitOfWork = _repository.UnitOfWork;
            _repository.Add(entity);
            unitOfWork.SaveChanges();
        }

        public void Update(T entity)
        {
            IUnitOfWork unitOfWork = _repository.UnitOfWork;
            _repository.Update(entity);
            unitOfWork.SaveChanges();
        }

        public void Save(T entity)
        {
            IUnitOfWork unitOfWork = _repository.UnitOfWork;
            _repository.Save(entity);
            unitOfWork.SaveChanges();
        }

        public IList<T> Find(Expression<Func<T, bool>> where)
        {
            IUnitOfWork unitOfWork = _repository.UnitOfWork;
            return _repository.Find(where).ToList();
        }

        public void Delete(T entity)
        {
            IUnitOfWork unitOfWork = _repository.UnitOfWork;
            _repository.Delete(entity);
            unitOfWork.SaveChanges();
        }

        public void Delete(Expression<Func<T, bool>> idSelector)
        {
            IUnitOfWork unitOfWork = _repository.UnitOfWork;
            T entity = _repository.Single(idSelector);
            _repository.Delete(entity);
            unitOfWork.SaveChanges();
        }
    }
}
